package com.weixiaodong.javabasic.Java注解.自定义注解案例1;

import com.weixiaodong.javabasic.Java注解.自定义注解案例1.annotation.Length;
import com.weixiaodong.javabasic.Java注解.自定义注解案例1.annotation.NotEmpty;
import com.weixiaodong.javabasic.Java注解.自定义注解案例1.annotation.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class main {

    @SuppressWarnings("all")
    public static String validate(Object o) throws IllegalAccessException {
        if (!(o instanceof Student)) return "传入的参数不是指定的检测类型(Student)";
        // 将o强制转化为Student类型
        Student student = (Student) o;

        // 获取studnet类型的所有字段
        Field[] fields = student.getClass().getDeclaredFields();

        // 逐个字段的进行注解校验
        for (Field field : fields) {

            StringBuilder error = new StringBuilder();

            // 检查这个字段是否标注了@NotNull注解
            if (field.isAnnotationPresent(NotNull.class)) {
                // 通过反射获取该字段上标注的@NotNull注解的详细信息
                NotNull annotation = field.getAnnotation(NotNull.class);
                // 设置访问权限
                field.setAccessible(true);
                // 通过反射获取对应的值
                String value = (String) field.get(student);
                if (value == null) {
                    error.append(annotation.message() + "; ");
                }
            }

            // 检查这个字段是否标注了@NotEmpty注解
            if (field.isAnnotationPresent(NotEmpty.class)) {
                NotEmpty annotation = field.getAnnotation(NotEmpty.class);
                field.setAccessible(true);
                String value = (String) field.get(student);
                if ("".equals(value)) {
                    error.append(annotation.message() + "; ");
                }
            }

            // 检查这个字段是否标注了@Length注解
            if (field.isAnnotationPresent(Length.class)) {
                Length annotation = field.getAnnotation(Length.class);
                field.setAccessible(true);
                int value = ((String) field.get(student)).length();
                if (value > annotation.max() || value < annotation.min()) {
                    error.append(annotation.message());
                }
            }

            System.out.println(error.toString());
        }
        return null;
    }


    public static void main(String[] args) throws IllegalAccessException {
        Student student = new Student();
        validate(student);
    }
}
